package com.spica.spicaschool.ui.newsdetail

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import coil.load
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.spica.spicaschool.base.BaseFragment
import com.spica.spicaschool.databinding.FragmentNewsDetailBinding
import com.spica.spicaschool.viewmodel.NewsDetailViewModel
import dagger.hilt.android.AndroidEntryPoint
import io.noties.markwon.Markwon
import timber.log.Timber
import javax.inject.Inject

/**
 * 新闻详情
 */
@AndroidEntryPoint
open class NewsDetailFragment : BaseFragment<FragmentNewsDetailBinding>() {

    @Inject
    lateinit var markwon: Markwon


    private val viewModel by viewModels<NewsDetailViewModel>()

    private var id = ""

    override fun init() {

        id = arguments?.getString("id") ?: ""
        viewModel.fetchNewsDetail(id, onStart = {
            requireActivity().runOnUiThread {
                WaitDialog.show("正在获取数据...")
            }
        }, onComplete = {
            requireActivity().runOnUiThread {
                WaitDialog.dismiss()
            }
        }, onError = {
            Timber.e("请求错误：${it}")
            requireActivity().runOnUiThread {
                TipDialog.show(it)
            }
        })
        //点击返回
        viewBinding.ivBack.setOnClickListener {
            findNavController().popBackStack()
        }
        //点击更多
        viewBinding.ivMore.setOnClickListener {

        }

        viewModel.newsLiveData.observe(this) {
            viewBinding.tvTitle.text = it.title
            viewBinding.tvKeyword.text = "关键字：${it.keywords}"
            markwon.setMarkdown(viewBinding.tvContent, it.content)
            viewBinding.ivHeadpic.load(it.headpic)
        }
    }


    override fun setupViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentNewsDetailBinding = FragmentNewsDetailBinding.inflate(inflater, container, false)
}